﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace MarvellousWorks.PracticalPatternNet8.SignletonPattern.SignletonN;

/// <summary>
/// 就是对象池技术
/// </summary>
public class Sigleton_N : IWorkItem
{
    private static int num = 0;
    private const int maxInstance = 2;
    private Status _status = Status.Free; // 初始化状态
    public Status Status { get => _status; set => _status = value; }

    public void DeActivate()
    {
        _status = Status.Free;
    }
    /// <summary>
    /// 添加了配置文件
    /// </summary>
    static Sigleton_N()
    {
        // 通过配置文件获取要创建实例的数量
        string? config = ConfigurationManager.AppSettings["maxInstance"];
        if (!string.IsNullOrEmpty(config))
            num = int.Parse(config);
        collection = new WorkItemCollection<Sigleton_N>(num);
    }

    //private static WorkItemCollection<Sigleton_N> collection = new WorkItemCollection<Sigleton_N>(maxInstance);
    private static WorkItemCollection<Sigleton_N> collection;
    private Sigleton_N() { }

    public static Sigleton_N? Instance
    {
        get
        {
            // 在基本实现框架不变的情况下，引入集合实现 Sigleton_N 的多个实例对象管理
            var instance = collection.GetWorkItem();
            if (instance == null)
            {
                if (!collection.CouldAddNewInstance)
                {
                    return null;
                }
                else
                {
                    instance = new Sigleton_N();
                    collection.Add(instance);
                }
            }
            instance.Status = Status.Busy;
            return instance;
        }
    }
}
